Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature / Fix: Allow Settings to be inherited and extended (fixes #644) #960

Merged

Conversation

dotKokott
Copy link
Contributor

@dotKokott dotKokott commented Jul 2, 2024

Before this would not work

from beanie import Document, init_beanie

class Sample1(Document):
    class Settings:
        name = "sample1"
        bson_encoders = {Color: lambda x: x.value}

class Sample2(Sample1):
    class Settings(Sample1.Settings):
        name = "sample2"
        
await init_beanie(
    database=db,
    document_models=[Sample2],
)        

assert Sample2.get_settings().bson_encoders != {} # Fails because Settings subclass completely overrides Sample1.Settings

The fastapi-users library actually claims in their documentation that this is how you should extend their BeanieBaseUser model to change the collection name: https://fastapi-users.github.io/fastapi-users/latest/configuration/databases/beanie/

Indeed the functionality would be very useful e.g. to provide shared bscon_encoders via a kind of base document model that all your documents inherit from.

This fixes #644 which was closed without resolution. In the issue @roman-right mentions that this is not fixable because it would have to be fixed via metaclass which is already occupied by pydantic. Evidently, by this PR, that is not the case :)

The way the Settings attribute collection was implemented before (via vars(class)) would throw away the inherited Settings if a Settings class was present in the inheriting class.

I changed the Settings attribute collection to use dir and included some filtering of dunder methods.

✅ Tests passing
✅ Added test to cover new functionality

I don't know if this fix / feature needs a change in the Settings documentation. Arguably it now behaves the way you'd expect this to behave, as it mirrors the way these attributes access and inherit via normal Python.

…low for partially inheriting settings from parent classes.
Copy link
Contributor

@adeelsohailahmed adeelsohailahmed left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me. Thank you for your contribution.

@adeelsohailahmed adeelsohailahmed merged commit 6ebcdf4 into BeanieODM:main Aug 21, 2024
19 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[BUG] get_settings() does not return the inherited settings
4 participants